# ui/log_window.py
import os

from PyQt5 import QtCore, QtWidgets, QtGui


class LogTailWorker(QtCore.QThread):
    log_updated = QtCore.pyqtSignal(str)

    def __init__(self, filepath):
        super().__init__()
        self.filepath = filepath
        self._running = True

    def run(self):
        with open(self.filepath, 'r', encoding='utf-8') as f:
            f.seek(0, os.SEEK_END)
            while self._running:
                line = f.readline()
                if line:
                    self.log_updated.emit(line)
                else:
                    self.msleep(200)  # sleep for 200ms

    def stop(self):
        self._running = False
        self.wait()
class LogWindow(QtWidgets.QWidget):
    def __init__(self,log_path):
        super().__init__()
        self.setWindowTitle("日志监控")
        self.setGeometry(0, 500, 500, 200)
        self.setWindowFlags(QtCore.Qt.Tool | QtCore.Qt.FramelessWindowHint | QtCore.Qt.WindowStaysOnTopHint)
        self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
        self.setWindowOpacity(0.9)
        self.log_path=log_path

        font = QtGui.QFont("Consolas", 10)
        layout = QtWidgets.QVBoxLayout(self)

        self.text_area = QtWidgets.QPlainTextEdit(readOnly=True)
        self.text_area.setFont(font)
        self.text_area.setStyleSheet("QPlainTextEdit { background-color: black; color: lightgreen; border: none; }")
        self.text_area.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.text_area.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        layout.addWidget(self.text_area)

        self.log_lines = []

        # 启动 tail worker
        self.tail_thread = LogTailWorker(self.log_path)
        self.tail_thread.log_updated.connect(self.append_log)
        self.tail_thread.start()

    def append_log(self, line):
        self.log_lines.append(line)
        self.log_lines = self.log_lines[-10:]  # 保留最后 10 行
        self.text_area.setPlainText("".join(self.log_lines))
        self.text_area.verticalScrollBar().setValue(
            self.text_area.verticalScrollBar().maximum()
        )

    def closeEvent(self, event):
        self.tail_thread.stop()
        event.accept()
